package com.zj.fx.controller.rpa;

import com.zj.fx.model.info.InfoSupply;
import com.zj.fx.model.info.InfoSupplyExample;
import com.zj.fx.model.rpa.*;
import com.zj.fx.service.info.InfoSupplyService;
import com.zj.fx.service.rpa.*;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @ClassName RpaScheduleTaskController
 * @Description TODO
 * @Author SQL--LIAONING
 * @Date 2023/10/27 13:50
 * @Version 1.0
 */
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling
public class RpaScheduleTaskController {

    @Autowired
    private RpaTaskService rpaTaskService;

    @Autowired
    private RpaTaskDtlService rpaTaskDtlService;

    @Autowired
    private RpaOriginaldataService rpaOriginaldataService;

    @Autowired
    private RpaMidSupplyService rpaMidSupplyService;

    @Autowired
    private RpaTransdataService rpaTransdataService;

    @Autowired
    private InfoSupplyService infoSupplyService;

    //供电可靠率数据同步
    //    @Scheduled(cron = "0/10 * * * * ?")
    //    private void updateReliability() {
    //        //每月10日同步上月可靠率
    //        String taskmonth = getYearandMonth();
    //        System.err.println("任务年份: " + taskmonth);
    //        //根据任务年月查询主任务
    //        //根据主任务查供电所task
    //        //根据供电所id查对应三方供电所名称
    //        //根据三方供电所名称查rpa可靠率中间表数据
    //        //更新对应供电所填报任务可靠率值
    //        //完成全部更新后记录同步日志
    //
    //    }

    /*
        获取当前年月
     */
    private String getYearandMonth() {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取当前年份
        int year = currentDate.getYear();
        // 获取当前月份
        int month = currentDate.getMonthValue();
        String smonth = "" + month;
        if (month <= 10) {
            month = month - 1;
            smonth = "0" + month;
        }
        if (month == 1) {
            smonth = "12";
            year = year - 1;
        }
        String taskmonth = year + smonth;
        return taskmonth;
    }

    /**
     * 每月月初生成RPA任务明细，根据主任务表中的开启状态逐个生成
     */
    @Scheduled(cron = "0 0 1 1 * ?")
    private void updateReliability() {
        //1、查询RPA任务主表中全部状态为开启的任务
        RpaTaskExample rpaTaskExample = new RpaTaskExample();
        rpaTaskExample.createCriteria().andEnabledEqualTo(RpaConstant.ENABLE);
        List<RpaTask> rpaTasks = rpaTaskService.selectByExample(rpaTaskExample);

        String lastYearandMonth = getLastYearandMonth();

        //2、生成对应的月度任务明细
        for (RpaTask rpaTask : rpaTasks) {
            String periodtype = rpaTask.getPeriodtype();

            RpaTaskDtl rpaTaskDtl = new RpaTaskDtl();
            rpaTaskDtl.setRpataskid(rpaTask.getId());
            rpaTaskDtl.setRpataskname(rpaTask.getName());
            rpaTaskDtl.setTargetid(rpaTask.getTargetid());
            rpaTaskDtl.setTypenum(rpaTask.getTypenum());
            rpaTaskDtl.setCreatetime(new Date());
            rpaTaskDtl.setTransstate(RpaConstant.NOT);
            rpaTaskDtl.setFillstate(RpaConstant.NOT);
            rpaTaskDtl.setPeriodtype(periodtype);
            if (RpaConstant.PERIOD_MONTH.equals(periodtype)) {

                //根据任务年月与typenum去查询原始数据推送接收表
                RpaOriginaldataExample rpaOriginaldataExample = new RpaOriginaldataExample();
                rpaOriginaldataExample.createCriteria().andTypenumEqualTo(rpaTask.getTypenum()).andTaskmonthEqualTo(lastYearandMonth);
                List<RpaOriginaldata> rpaOriginaldata = rpaOriginaldataService.selectByExample(rpaOriginaldataExample);
                if (rpaOriginaldata!=null && rpaOriginaldata.size()>0){
                    rpaTaskDtl.setPushstate(RpaConstant.IS);
                    rpaTaskDtl.setPushcount(String.valueOf(rpaOriginaldata.size()));
                }else {
                    rpaTaskDtl.setPushstate(RpaConstant.NOT);
                }
                rpaTaskDtl.setTaskmonth(lastYearandMonth);
                rpaTaskDtlService.insertSelective(rpaTaskDtl);
            } else if (RpaConstant.PERIOD_QUTAR.equals(periodtype)) {
                //Todo 季度类型
//                LocalDate currentDate = LocalDate.now();
//                int month = currentDate.getMonthValue() - 1;
//                if (month % 3 == 0) {
//                    rpaTaskDtl.setTaskmonth(lastYearandMonth);
//                    rpaTaskDtlService.insertSelective(rpaTaskDtl);
//                }
            }
            //TODO 待完善  --缺少其他类型，如年度
        }
    }

    /*
        获取当前年月
     */
    private String getLastYearandMonth() {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取当前年份
        int year = currentDate.getYear();
        // 获取当前月份
        int month = currentDate.getMonthValue();
        String smonth;
        if (month <= 10) {
            month = month - 1;
            smonth = "0" + month;
        } else {
            month = month - 1;
            smonth = "" + month;
        }
        if (month == 0) {
            smonth = "12";
            year = year - 1;
        }
        String taskmonth = year + smonth;
        return taskmonth;
    }

    /**
     * 每月1日3时转换上月有效数据
     */
    @Scheduled(cron = "0 0 3 1 * ?")
    private void transeffdata() {
        //1、查询任务明细表中存在的任务明细（上一月份）如：11月初查询生成的10月份数据RPA明细
        String lastmonth = getLastYearandMonth();
        RpaTaskDtlExample rpaTaskDtlExample = new RpaTaskDtlExample();
        rpaTaskDtlExample.createCriteria().andTaskmonthEqualTo(lastmonth);
        List<RpaTaskDtl> rpaTaskDtls = rpaTaskDtlService.selectByExample(rpaTaskDtlExample);
        //2、通过业务分类编号查询RPA中原始数据表中的数据，根据周期类型进行不同形式的计算
        for (RpaTaskDtl rpaTaskDtl : rpaTaskDtls) {
            String periodtype = rpaTaskDtl.getPeriodtype();

            int totalOld = 0; //原始数据总数
            int successcount = 0;
            int failcount = 0;

            if (RpaConstant.PERIOD_MONTH.equals(periodtype)) {
                RpaOriginaldataExample rpaOriginaldataExample = new RpaOriginaldataExample();
                rpaOriginaldataExample.createCriteria().andTaskmonthEqualTo(getLastYearandMonth()).andTypenumEqualTo(rpaTaskDtl.getTypenum());
                List<RpaOriginaldata> rpaOriginaldata = rpaOriginaldataService.selectByExample(rpaOriginaldataExample);
                totalOld = rpaOriginaldata.size();

                for (RpaOriginaldata rpaOriginaldatum : rpaOriginaldata) {

                    RpaTransdata rpaTransdata = new RpaTransdata();
                    rpaTransdata.setTaskmonth(rpaOriginaldatum.getTaskmonth());
                    rpaTransdata.setThirdid(rpaOriginaldatum.getThirdid());
                    rpaTransdata.setSubcompanyname(rpaOriginaldatum.getSubcompanyname());
                    rpaTransdata.setTypenum(rpaOriginaldatum.getTypenum());
                    rpaTransdata.setTypename(rpaOriginaldatum.getTypename());
                    rpaTransdata.setTargetid(rpaTaskDtl.getTargetid());
                    //匹配供电所名称对称表
                    if (RpaConstant.IS.equals(rpaOriginaldatum.getIsmatch())) {
                        RpaMidSupplyExample rpaMidSupplyExample = new RpaMidSupplyExample();
                        if (RpaConstant.TYPE_GONGDIAN_NUM.equals(rpaTaskDtl.getTypenum())) {
                            rpaMidSupplyExample.createCriteria().andThirdname1EqualTo(rpaOriginaldatum.getSupplyname());
                        }
                        List<RpaMidSupply> rpaMidSupplies = rpaMidSupplyService.selectByExample(rpaMidSupplyExample);
                        if (rpaMidSupplies.size()!=1){
                            failcount++;
                            continue;
                        }else {
                            rpaTransdata.setSelfsupplyid(rpaMidSupplies.get(0).getSupplyid());
                            rpaTransdata.setSelfsupplyname(rpaMidSupplies.get(0).getSupplyname());
                            //Todo 这里暂未做业务类型区分，先以供电可靠率做默认
                            rpaTransdata.setSupplyname(rpaMidSupplies.get(0).getThirdname1());
                        }
                    } else {
                        //根据名称查询系统供电所表获取id
                        InfoSupplyExample infoSupplyExample = new InfoSupplyExample();
                        infoSupplyExample.createCriteria().andNameEqualTo(rpaOriginaldatum.getSupplyname());
                        List<InfoSupply> supplyList = infoSupplyService.selectByExample(infoSupplyExample);
                        if (supplyList.size()!=1){
                            failcount++;
                            continue;
                        }else {
                            rpaTransdata.setSelfsupplyid(supplyList.get(0).getId());
                            rpaTransdata.setSelfsupplyname(supplyList.get(0).getName());
                        }
                    }

                    //------------数据处理START-----------------
                    if (RpaConstant.NOT.equals(rpaOriginaldatum.getIscombine())){
                        rpaTransdata.setDatamemo(rpaOriginaldatum.getDatamemo1());
                        rpaTransdata.setValue(rpaOriginaldatum.getValue1());
                    }else {
                        //Todo 需要混合计算的逻辑，待具体需求确定后补充
                    }
                    //------------数据处理END-----------------

                    if (Strings.isNotBlank(rpaTransdata.getValue())){ //保证数据严谨性，有值才转换
                        rpaTransdata.setCreatetime(new Date());
                        rpaTransdataService.insertSelective(rpaTransdata);
                        successcount++;

                        //更改原始数据表单条状态（是否转换为有效数据）
                        rpaOriginaldatum.setIstransfer(RpaConstant.IS);
                        rpaOriginaldatum.setTranstime(new Date());
                        rpaOriginaldataService.updateByPrimaryKeySelective(rpaOriginaldatum);
                    }
                }
            }
            //Todo 目前仅满足月度周期数据转换，其他类型待具体需求满足后进行开发

            //更改rpa月度任务明细表中的转换状态
            rpaTaskDtl.setTransstate(RpaConstant.IS);
            rpaTaskDtl.setTranscount(String.valueOf(successcount));
            rpaTaskDtl.setTranstime(new Date());
            rpaTaskDtlService.updateByPrimaryKeySelective(rpaTaskDtl);

        }
    }

}
